package com.macro.mall.service.impl;
import com.github.rholder.retry.*;
import com.google.common.collect.Lists;


import cn.hutool.core.util.ObjectUtil;
import com.fasterxml.jackson.databind.ObjectMapper;

import com.macro.mall.common.api.CommonResult;
import com.macro.mall.common.config.XhsApiConfig;
import com.macro.mall.common.exception.XhsApiException;
import com.macro.mall.dto.ProductSyncRequest;
import com.macro.mall.dto.ProductSyncResponse;
import com.macro.mall.dto.UmsMenuNode;
import com.macro.mall.mapper.PmsProductMapper;
import com.macro.mall.model.PmsProduct;
import com.macro.mall.model.request.ProductBatchGetRequest;
import com.macro.mall.model.request.ProductGetRequest;
import com.macro.mall.model.request.SkuBatchDeleteRequest;
import com.macro.mall.model.response.ProductBatchGetResponse;
import com.macro.mall.model.response.ProductGetResponse;
import com.macro.mall.model.response.SkuBatchDeleteResponse;
import com.macro.mall.model.vo.ProductDataVo;
import com.macro.mall.model.vo.product.ProductDetailVo;
import com.macro.mall.model.vo.product.ProductListVo;
import com.macro.mall.service.ProductSyncService;
import com.macro.mall.service.XhsLoginService;
import com.macro.mall.service.XhsProductService;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import okhttp3.HttpUrl;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class ProductSyncServiceImpl implements ProductSyncService {

    @Value("${xhs.app-id}")
    private String appId;

    private final OkHttpClient httpClient;
    private final ObjectMapper objectMapper;

    @Resource
    private XhsApiConfig apiConfig;

    @Resource
    private XhsProductService xhsProductService;


    @Resource
    private PmsProductMapper productMapper;

    @Resource
    private XhsLoginService xhsLoginService;

    public ProductSyncServiceImpl(OkHttpClient httpClient, ObjectMapper objectMapper) {
        this.httpClient = httpClient;
        this.objectMapper = objectMapper;
    }

    @Override
    public ProductSyncResponse syncProduct(ProductSyncRequest request) {
        String apiUrl = "https://miniapp-sandbox.xiaohongshu.com/api/rmp/mp/deal/poi/product/upsert";

        try {
            // 1. 将业务参数转换为JSON
            String jsonBody = objectMapper.writeValueAsString(request);
            String validToken = null;
            try {
                validToken = xhsLoginService.getValidToken();
            } catch (XhsApiException e) {
                throw new RuntimeException(e);
            }
            // 2. 构建带公共参数的URL
            HttpUrl url = HttpUrl.parse(apiUrl).newBuilder()
                    .addQueryParameter("app_id", appId)
                    .addQueryParameter("access_token",validToken )
                    .build();

            // 3. 构建请求
            Request httpRequest = new Request.Builder()
                    .url(url)
                    .post(RequestBody.create(jsonBody, MediaType.parse("application/json")))
                    .addHeader("Content-Type", "application/json")
                    .build();
            // 3. 执行请求
            try (Response response = httpClient.newCall(httpRequest).execute()) {
                if (!response.isSuccessful()) {
                    log.error("商品同步失败，HTTP状态码: {}", response.code());
                    return new ProductSyncResponse();
                }

                // 4. 解析响应
                String responseBody = response.body().string();
                return objectMapper.readValue(responseBody, ProductSyncResponse.class);
            }
        } catch (IOException e) {
            log.error("商品同步异常", e);
            return new ProductSyncResponse();
        }
    }













    @Override
    public ProductBatchGetResponse batchGetProducts(ProductBatchGetRequest request) {
        String apiUrl = apiConfig.getBaseUrl() + "/api/rmp/mp/deal/product/batch_get";

        // 定义重试策略
        Retryer<ProductBatchGetResponse> retryer = RetryerBuilder.<ProductBatchGetResponse>newBuilder()
                .retryIfException() // 所有异常都重试
                .retryIfResult(response -> response == null) // 返回值为null时重试
                .withWaitStrategy(WaitStrategies.fixedWait(1, TimeUnit.SECONDS)) // 固定间隔1秒
                .withStopStrategy(StopStrategies.stopAfterAttempt(5)) // 最多重试3次
                .build();

        try {
            return retryer.call(() -> {
                try {
                    String validToken = xhsLoginService.getValidToken();
                    HttpUrl url = HttpUrl.parse(apiUrl).newBuilder()
                            .addQueryParameter("app_id", apiConfig.getAppId())
                            .addQueryParameter("access_token", validToken)
                            .build();

                    String jsonBody = objectMapper.writeValueAsString(request);
                    RequestBody body = RequestBody.create(jsonBody, MediaType.parse("application/json"));

                    Request httpRequest = new Request.Builder()
                            .url(url)
                            .post(body)
                            .addHeader("Content-Type", "application/json")
                            .build();

                    try (Response response = httpClient.newCall(httpRequest).execute()) {
                        if (!response.isSuccessful()) {
                            log.error("商品批量获取失败，HTTP状态码: {}, 请求参数: {}", response.code(), jsonBody);
                            throw new RuntimeException("API请求失败，状态码: " + response.code());
                        }
                        String responseBody = response.body().string();
                        return objectMapper.readValue(responseBody, ProductBatchGetResponse.class);
                    }
                } catch (IOException e) {
                    log.error("商品批量获取异常，请求参数: {}", request, e);
                    throw new RuntimeException("商品批量获取异常", e);
                }
            });
        } catch (RetryException | ExecutionException e) {
            log.error("商品批量获取重试3次后仍失败，请求参数: {}", request, e);
            throw new RuntimeException("商品批量获取重试多次后失败", e);
        }
    }








    @Override
    public ProductGetResponse getProduct(ProductGetRequest request) {
        String apiUrl = apiConfig.getBaseUrl() + "/api/rmp/mp/deal/product/get";

        String validToken = null;
        try {
            validToken = xhsLoginService.getValidToken();
        } catch (XhsApiException e) {
            throw new RuntimeException(e);
        }

        try {
            // 1. 构建请求URL
            HttpUrl url = HttpUrl.parse(apiUrl).newBuilder()
                    .addQueryParameter("app_id", apiConfig.getAppId())
                    .addQueryParameter("access_token", validToken)
                    .build();

            // 2. 构建请求体
            String jsonBody = objectMapper.writeValueAsString(request);
            RequestBody body = RequestBody.create(jsonBody, MediaType.parse("application/json"));

            // 3. 构建请求
            Request httpRequest = new Request.Builder()
                    .url(url)
                    .post(body)
                    .addHeader("Content-Type", "application/json")
                    .build();

            // 4. 执行请求
            try (Response response = httpClient.newCall(httpRequest).execute()) {
                if (!response.isSuccessful()) {
                    log.error("商品获取失败，HTTP状态码: {}", response.code());
                    throw new RuntimeException("API请求失败，状态码: " + response.code());
                }

                // 5. 解析响应
                String responseBody = response.body().string();
                return objectMapper.readValue(responseBody, ProductGetResponse.class);
            }
        } catch (IOException e) {
            log.error("商品获取异常", e);
            throw new RuntimeException("商品获取异常", e);
        }
    }





    @Override
    public  List<ProductListVo>  getProductList(ProductBatchGetRequest request) {

        ProductBatchGetResponse productBatchGetResponse = batchGetProducts(request);
        ProductBatchGetResponse.ProductBatchGetData data = productBatchGetResponse.getData();
        if (ObjectUtil.isNull(data)){
            return null;
        }
        List<ProductListVo> productListVos = new ArrayList<>();
        List<ProductBatchGetResponse.ProductItem> productItemList = productBatchGetResponse.getData().getList();
        productItemList.stream().forEach(productItem -> {
            ProductListVo productListVo = new ProductListVo();
            BeanUtils.copyProperties(productItem, productListVo);
            PmsProduct product = productMapper.getById(Integer.valueOf(productListVo.getOutProductId()));
            if (ObjectUtil.isNotEmpty(product)){
                productListVo.setSale(product.getSale());
                productListVo.setOriginPrice(product.getOriginalPrice());
                productListVo.setSalePrice(product.getPrice());

                BigDecimal salePrice = productListVo.getSalePrice();
                BigDecimal originPrice = productListVo.getOriginPrice();

                // 默认不打折
                double discount = 10.0;

                // 安全计算折扣
                if (originPrice != null && originPrice.compareTo(BigDecimal.ZERO) > 0) {
                    discount = salePrice.divide(originPrice, 4, RoundingMode.HALF_UP)
                            .multiply(BigDecimal.TEN)
                            .setScale(1, RoundingMode.HALF_UP)
                            .doubleValue();
                }
                // 设置折扣
                productListVo.setDiscount(discount);
            }

            productListVos.add(productListVo);

        });

        return productListVos;


    }

    @Override
    public SkuBatchDeleteResponse batchDeleteSkus(SkuBatchDeleteRequest request) {
        // 验证SKU数量不超过100个
        if (request.getOutSkuIds().size() > 100) {
            throw new IllegalArgumentException("单次删除SKU数量不能超过100个");
        }

        String apiUrl = apiConfig.getBaseUrl() + "/api/rmp/mp/deal/product/sku/batch_delete";


        String validToken = null;
        try {
            validToken = xhsLoginService.getValidToken();
        } catch (XhsApiException e) {
            throw new RuntimeException(e);
        }
        try {
            // 1. 构建请求URL
            HttpUrl url = HttpUrl.parse(apiUrl).newBuilder()
                    .addQueryParameter("app_id", apiConfig.getAppId())
                    .addQueryParameter("access_token", validToken)
                    .build();

            // 2. 构建请求体
            String jsonBody = objectMapper.writeValueAsString(request);
            RequestBody body = RequestBody.create(jsonBody, MediaType.parse("application/json"));

            // 3. 构建请求
            Request httpRequest = new Request.Builder()
                    .url(url)
                    .post(body)
                    .addHeader("Content-Type", "application/json")
                    .build();

            // 4. 执行请求
            try (Response response = httpClient.newCall(httpRequest).execute()) {
                if (!response.isSuccessful()) {
                    log.error("SKU批量删除失败，HTTP状态码: {}", response.code());
                    throw new RuntimeException("API请求失败，状态码: " + response.code());
                }

                // 5. 解析响应
                String responseBody = response.body().string();
                return objectMapper.readValue(responseBody, SkuBatchDeleteResponse.class);
            }
        } catch (IOException e) {
            log.error("SKU批量删除异常", e);
            throw new RuntimeException("SKU批量删除异常", e);
        }
    }

    @Override
    public ProductDetailVo getDetailProduct(Integer id) {
        ProductGetRequest request = new ProductGetRequest();
        request.setOutProductId(String.valueOf(id));
        ProductGetResponse product = xhsProductService.getProduct(request);


        ProductDetailVo productDetailVo = new ProductDetailVo();
        BeanUtils.copyProperties(product.getData(), productDetailVo);
        PmsProduct products = productMapper.getById(Integer.valueOf(id));
        if (ObjectUtil.isNotEmpty(products)){
            productDetailVo.setSale(products.getSale());
            productDetailVo.setOriginPrice(products.getOriginalPrice());
            productDetailVo.setSalePrice(products.getPrice());

            BigDecimal salePrice = productDetailVo.getSalePrice();
            BigDecimal originPrice = productDetailVo.getOriginPrice();

            // 默认不打折
            double discount = 10.0;

            // 安全计算折扣
            if (originPrice != null && originPrice.compareTo(BigDecimal.ZERO) > 0) {
                discount = salePrice.divide(originPrice, 4, RoundingMode.HALF_UP)
                        .multiply(BigDecimal.TEN)
                        .setScale(1, RoundingMode.HALF_UP)
                        .doubleValue();
            }
            // 设置折扣
            productDetailVo.setDiscount(discount);
        }
        return productDetailVo;
    }
}
